/*
 * Copyright 2007 National Bioinformatics Network
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package dgbgui.tools;

import java.awt.event.ActionEvent;
import java.util.Set;

import dgbgui.DGBGUI;
import dgbgui.command.AddQueryCommand;
import dgbgui.command.Command;
import dgbgui.command.CommandStack;
import dgbgui.command.ReplaceQueryCommand;
import dgbgui.gui.dialogs.CustomQueryDialog;
import dgbgui.modeldocument.Query;
import dgbgui.modeldocument.definition.CustomDefinition;
import dgbgui.modeldocument.definition.Definition;
import dgbgui.selection.SelectionManager;

public class CustomQueryTool extends DialogedTool {
    
    //  TODO: refactor
    public static enum ToolType { CREATE, EDIT };
    
    public CustomQueryTool(ToolType type) {
        m_type = type;
    }

    public void execute() {
        
        String dgbQLString = "";
        if ( m_type == ToolType.EDIT ) {
            Set<Object> queries = SelectionManager.getInstance().getSelection(Query.class);
            assert ( queries.size() == 1);
            m_query = (Query)(queries.iterator().next());
            Definition def = m_query.getDefinition();
            assert ( def instanceof CustomDefinition );
            dgbQLString = def.getdgbQLString();
        }
        
        // Create the m_dialog for editing the attributes. 
        // the true parameter indicates that the m_dialog should be modal
        m_dialog = new CustomQueryDialog(this,dgbQLString);
        m_dialog.pack();
        DGBGUI.centerDialog(m_dialog);
        m_dialog.setVisible(true);
        
    }

    public void actionPerformed(ActionEvent event) {

        if ( event.getSource() == m_dialog.getOkButton() ) {
            
            
            // Update all the properties
            Definition def = new CustomDefinition(((CustomQueryDialog)m_dialog).getDGBQL());
            Query newQuery = new Query(def);

            // Replace/create
            Command command;
            if ( m_type == ToolType.CREATE ) {
                command = new AddQueryCommand(newQuery);
            } else {
                command = new ReplaceQueryCommand(m_query,newQuery);
            }
                
            CommandStack.getInstance().execute(command);
        }
        

        // Close the tool
        doClose();

    }

    private ToolType m_type;
    private Query m_query;
}
